package com.briup.ch02;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;
import java.util.Arrays;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/11/6
 * @Description:
 */
public class Test02 {
    //连接4要素
    private String driverClass="com.mysql.cj.jdbc.Driver";
    private String url="jdbc:mysql://localhost:3306/briup";
    private String username="briup";
    private String password="briup";
    //资源对象
    Connection conn=null;
    Statement stmt=null;
    ResultSet rs=null;

    //设置连接对象，SQL操作对象
    @Before
    public void canDo() {
        try {
            //1.类加载驱动
            Class.forName(driverClass);
            //2.获取连接对象
            conn=DriverManager.getConnection(url,username,password);
            //3.获取SQL操作对象
            stmt=conn.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    @After
    public void close() {
        try {
            if(rs!=null) rs.close();
            if(stmt!=null) stmt.close();
            if(conn!=null) conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void batch(){
        String sql1="drop table if exists user";
        String sql2="create table user(id int primary key auto_increment,name varchar(50) unique,password varchar(50))";
        String sql3="insert into user(name,password) values('tom','123456')";
        String sql4="insert into user(name,password) values('jerry','654321')";
        String sql5="insert into user(name,password) values('lily','abcdef')";
        try {
            //batch一般是执行DML和DDL语句，一般不执行DQL语句
            stmt.addBatch(sql1);
            stmt.addBatch(sql2);
            stmt.addBatch(sql3);
            stmt.addBatch(sql4);
            stmt.addBatch(sql5);
            int[] count=stmt.executeBatch();
            System.out.println(Arrays.toString(count));

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
